package com.dao.impl;

import java.sql.*;

public class BaseDao {
    private String driver = "com.mysql.jdbc.Driver";
    private String user = "root";
    private String password = "admin";
    private String url = "jdbc:mysql://localhost:3306/booking?useUnicode=true&characterEncoding=utf8";

    private Connection connection = null;
    private PreparedStatement pstmt = null;

    //获取连接
    public Connection getConnection(){
        try {
            Class.forName(driver);
            System.out.println("驱动已加载");
            connection = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        return connection;
    }

    //通用增删改方法
    public int executeUpdateSql(String sql,Object[] obj){
        connection = getConnection();
        try {
            pstmt =connection.prepareStatement(sql);
            if (pstmt != null && obj != null){
                for (int i = 0;i< obj.length;i++){
                    pstmt.setObject(i+1,obj[i]);
                }

                return pstmt.executeUpdate();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            closeAll(null,pstmt,connection);
        }

        return 0;
    }

    //通用查询方法
    public PreparedStatement executeQuerySql(String sql,Object[] obj,Connection connection){
        try {
            pstmt = connection.prepareStatement(sql);
            if (pstmt != null){
                for (int i = 0;i < obj.length;i++){
                    pstmt.setObject(i+1,obj[i]);
                }

                return pstmt;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;
    }

    //关闭连接通道
    public void closeAll(ResultSet rs,Statement pstmt,Connection connection) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
